var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var mysql      = require('mysql');

var routes = require('./routes/index');
var users = require('./routes/users');
var orders = require('./routes/orders');
var coupons = require('./routes/coupons');

var ds = null;
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req,res,next){
    req.ds = ds;
    next();
});

app.use('/', routes);
app.use('/users', users);
app.use('/orders',orders);
app.use('/coupons',coupons);



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

//=================== mysql database ====
/* var connection = mysql.createConnection(
  'mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700');

    connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
      if (err) throw err;
      console.log('The solution is: ', rows[0].solution);
    });
    connection.end();
*/


  ds = mysql.createPool({
    host     : '**.mysql.rds.aliyuncs.com',
    database : '**',
    user     : '**',
    password: "**", 
    port: "3306", 
    dateStrings : true,
    connectionLimit : 2,
    queueLimit : 5,
    debug : false
  });

  ds.on('connection', function (conn) {
    console.log('init connection as id ' + conn.threadId);
    //connection.query('SET SESSION auto_increment_increment=1')
  });

  ds.on('enqueue', function () {
    console.log('Waiting for available connection slot');
  });

  ds.getConnection(function(err, conn) {
    conn.query( 'SELECT "1" "id","title sample" "title","www.baidu.com" "feed" as podcasts', function(error, results, fields) {
      console.log("sample result is :",results);
      conn.release();
    });
  });

  /*
  pool.end(function (err) {
    // all connections in the pool have ended
  });
  */

  //=================== mysql database ====


module.exports = app;
